import React, { useCallback, useState } from 'react'
import { nanoid } from 'nanoid';

export default function App() {
    const [text, setText] = useState("");
    const [list, setList] = useState([
        {
            id: nanoid(),
            name: "张三",
            isChecked: false,
        }
    ])
    const [defaultChecked, setDefaultChecked] = useState(false)

    const handlerInput = useCallback(
        (evt) => {
            setText(evt.target.value)
        }, []
    )

    const handlerAdd = useCallback(
        () => {
            setList([...list, {
                id: nanoid(),
                name: text,
                isChecked: defaultChecked,
            }])
            setText("")
        }, [text, list, defaultChecked]
    )

    const handlerDelete = useCallback(
        (index) => {
            var newList = [...list];
            newList.splice(index, 1)
            setList(newList)
        }, [list]
    )

    const handlerChecked = useCallback(
        (index) => {
            var newList = [...list];
            newList[index].isChecked = !newList[index].isChecked
            setList(newList)
            console.log(list);
        }, [list]
    )

    const handlerIfFinish = useCallback(
        (evt) => {
            setDefaultChecked(evt.target.checked)
        }, []
    )
    return (
        <div>
            <input onChange={handlerInput} value={text} />
            <button onClick={handlerAdd}>Add</button>
            <input type="checkbox" onChange={handlerIfFinish} />是否完成
            <ul>
                {
                    list.map((item, index) =>
                        <li key={item.id}>
                            <input type="checkbox" checked={item.isChecked} onChange={() => {
                                handlerChecked(index)
                            }} />
                            <span style={{ textDecoration: item.isChecked ? "line-through" : "" }}>{item.name}</span>
                            <button onClick={() => {
                                handlerDelete(index)
                            }}>delete</button>
                        </li>
                    )
                }
            </ul>
            {list.length === 0 && <div>暂无数据</div>}
        </div>
    )
}
